
package cn.xd.base.persistence.repository.impl;

import cn.hutool.core.util.StrUtil;
import cn.xd.base.basic.type.DictGroupId;
import cn.xd.base.basic.type.DictGroupName;
import cn.xd.base.domain.entity.DictGroup;
import cn.xd.base.domain.repository.DictGroupRepository;
import cn.xd.base.domain.repository.KeyValueRepository;
import cn.xd.base.persistence.dos.DictGroupConverter;
import cn.xd.base.persistence.dos.DictGroupDO;
import cn.xd.base.persistence.mps.DictGroupMpService;
import cn.xd.base.persistence.mps.DictMpService;
import cn.xd.base.persistence.mps.KeyValueMpService;
import cn.xd.core.ddd.db.DbRepositorySupport;
import cn.xd.core.ddd.diff.EntityDiff;
import cn.xd.core.response.ObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

/**
 * @author : mirzaLin
 * @data : 2023/11/20
 * @description :
 **/
@Repository
public class DictGroupRepositoryImpl extends DbRepositorySupport<DictGroup, DictGroupId> implements DictGroupRepository {
    @Resource
    private DictMpService dictMpService;
    @Resource
    private KeyValueMpService keyValueMpService;
    @Resource
    private KeyValueRepository keyValueRepository;

    @Resource
    private DictGroupMpService dictGroupMpService;

    @Override
    protected void onInsert(DictGroup aggregate) {
        // 检查，验证字典编码（Code）不可重复
        find(aggregate.getName()).isNotEmptyThrow("存在重名的字典编码");
        dictGroupMpService.saveResult(aggregate, DictGroupConverter.INSTANCE);
    }

    @Override
    protected DictGroup onSelect(DictGroupId id) {
        return dictGroupMpService.getResult(id, DictGroupConverter.INSTANCE).get();
    }

    @Override
    protected void onUpdate(DictGroup aggregate, EntityDiff diff) {
        if (diff.isSelfModified()) {
            DictGroupDO bean = diff.getBean(DictGroupDO.class);
            // 检查，字典编码（Code）若修改则验证不可重复
            if (StrUtil.isNotBlank(bean.getName())) {
                find(DictGroupName.of(bean.getName())).isNotEmptyThrow("存在重名的字典分组");
            }
            dictGroupMpService.updateResult(bean);
        }
    }

    @Override
    protected void onDelete(DictGroup aggregate) {

    }

    /**
     * 通过字典编码查找一条记录
     *
     * @param name 字典编码
     * @return 字典
     */
    @Override
    public ObjectResult<DictGroup> find(DictGroupName name) {
        LambdaQueryWrapper<DictGroupDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(name.getValue()), DictGroupDO::getName, name.getValue());
        DictGroup dictGroup = dictGroupMpService.getOneForLimitOneResult(wrapper, DictGroupConverter.INSTANCE).isNotEmpty(this::attach);
        return ObjectResult.of(dictGroup);
    }
}
